package storage

import (
	"encoding/csv"
	"io"
	"os"
	"runtime"

	"gitee.com/yrwy/msgo/pkg/mem"
)

type CsvStore struct {
	closer func() error
	cw     *csv.Writer
}

func NewCsvStore(w io.Writer) *CsvStore {
	r := &CsvStore{}
	r.cw = csv.NewWriter(w)
	return r
}

func NewCsvFile(name string) (*CsvStore, error) {
	w, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm)
	if err != nil {
		return nil, err
	}
	runtime.SetFinalizer(w, (*os.File).Close)
	r := NewCsvStore(w)
	return r, nil
}

func (x *CsvStore) Write(d IData) error {
	row := d.GetRow()
	line := make([]string, len(row))
	for i, cell := range row {
		line[i] = mem.ToString(cell)
	}
	return x.cw.Write(line)
}

func (x *CsvStore) Writes(ds []IData) (int, error) {
	for i, d := range ds {
		err := x.Write(d)
		if err != nil {
			return i, err
		}
	}
	return len(ds), nil
}
